<template>
  <div class="order-container">
    <!-- 订单搜索区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="订单编号">
        <el-input v-model="searchForm.orderId" placeholder="请输入查询订单编号"/>
      </el-form-item>
      <el-form-item label="客户">
        <el-select v-model="searchForm.customerId" placeholder="请选客户" style="width: 100px">
          <el-option
              v-for="item in customerOptions"
              :key="item.customerId"
              :label="item.name"
              :value="item.customerId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchForm.status" placeholder="请选订单状态" style="width: 140px">
          <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
        <span style="margin: 0 10px">--</span>
        <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOrders">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表区域 -->
    <el-table :data="orderList" border style="width: 100%">
      <el-table-column prop="orderId" width="210px" label="订单编号"/>
      <el-table-column prop="name" width="90px" label="订单客户"/>
      <el-table-column prop="address" width="190px" label="收货地址"/>
      <el-table-column prop="totalPrice" width="90px" label="总金额"/>
      <el-table-column prop="statusName" width="90px" label="订单状态"/>
      <el-table-column prop="createTime" width="200px" label="下单时间"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row.orderId)"
              :disabled="![0, -1].includes(scope.row.status)"
          >修改
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="handleDetail(scope.row.orderId)"
          >订单详情
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.orderId, scope.row.name)"
          >删除
          </el-button>
          <el-button
              type="warning"
              size="small"
              @click="submitApproval(scope.row.orderId)"
              :disabled="![0, -1].includes(scope.row.status)"
          >提交审批
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="pay(scope.row.orderId)"
              :disabled="scope.row.status !== 1"
          >
            支付
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 4, 5,]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: center;"
    />

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" v-model="detailDialogVisible" width="60%">
      <el-table :data="orderDetail" border style="width: 100%">
        <el-table-column prop="name" label="商品名称"/>
        <el-table-column prop="buyNum" label="商品数量"/>
        <el-table-column prop="price" label="商品单价"/>
        <el-table-column prop="sumPrice" label="总计"/>
      </el-table>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        title="提示"
        v-model="deleteDialogVisible"
        width="30%"
        @close="deleteDialogVisible = false"
    >
      <div>您确定删除客户{{ deleteCustomerName }}的订单吗, 是否继续?</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑订单弹窗 -->
    <el-dialog title="修改订单信息" v-model="editDialogVisible" width="80%">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="订单客户">
          <el-input v-model="editForm.customerName" disabled/>
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="editForm.address" disabled/>
        </el-form-item>

        <h3>订单项</h3>
        <el-table :data="editForm.items" border style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="name" label="商品名称"/>
          <el-table-column label="商品数量">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.buyNum"
                  :min="1"
                  @change="() => calculateItemSum(scope.row)"
                  size="small"
              />
              <span>斤</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="商品单价"/>
          <el-table-column prop="sumPrice" label="小计"/>
        </el-table>

        <el-form-item label="订单金额">
          <el-input-number
              v-model.number="editForm.totalPrice"
              :min="0"
              :step="0.01"
              :precision="2"
              readonly
          />
          <span>元</span>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="editForm.status" placeholder="请选订单状态">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
          <el-date-picker
              v-model="editForm.createTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加订单弹窗 -->
    <el-dialog title="添加订单" v-model="addDialogVisible" width="90%">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="120px">
        <!-- 客户选择 -->
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="addForm.customerId" placeholder="请选择客户" style="width: 30%">
            <el-option
                v-for="item in customerOptions"
                :key="item.customerId"
                :label="item.name"
                :value="item.customerId"
            />
          </el-select>
        </el-form-item>
        <!-- 地址选择 -->
        <el-form-item label="地址" prop="addressId">
          <el-select v-model="addForm.addressId" placeholder="请选择地址" style="width: 30%">
            <el-option
                v-for="item in addressOptions"
                :key="item.addressId"
                :label="`${item.address} - ${item.detailAddress}`"
                :value="item.addressId"
            />
          </el-select>
        </el-form-item>

        <!-- 商品项列表 -->
        <div
            v-for="(item, index) in addForm.items"
            :key="index"
            style="margin-bottom: 15px; display: flex; align-items: center"
        >
          <el-form-item label="商品" :prop="`items[${index}].productId`"
                        :rules="[{ required: true, message: '请选择商品', trigger: 'change' }]">
            <el-select
                v-model="item.productId"
                placeholder="请选商品"
                @change="handleProductChange($event, index)"
                style="width: 120px"
            >
              <el-option
                  v-for="prod in productOptions"
                  :key="prod.productId"
                  :label="prod.name"
                  :value="prod.productId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" :prop="`items[${index}].buyNum`"
                        :rules="[{ required: true, message: '请输入数量', trigger: 'blur' }]">
            <el-input-number
                v-model="item.buyNum"
                :min="1"
                @change="() => calculateAddItemSum(index)"
            />
            <span>斤</span>
          </el-form-item>
          <el-button
              type="danger"
              @click="removeAddItem(index)"
              style="margin-left: 20px;margin-bottom: 15px"
          >清空
          </el-button>
        </div>
        <el-form-item label="总额">
          <el-input v-model.number="addForm.totalPrice" style="width: 10%;" placeholder="总额" readonly/>
          <span>元</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addNewItem">新增商品</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </template>
    </el-dialog>

    <!-- 添加订单按钮 -->
    <el-button type="primary" style="margin-top: 10px" @click="addDialogVisible = true">添加订单</el-button>

    <!-- 导出订单按钮 -->
    <el-button type="success" style="margin-top: 10px; margin-left: 10px" @click="handleExport">导出订单</el-button>
  </div>
</template>

<script>
import {
  findSearchOrders,
  findOrderDetail,
  deleteOrder,
  getOrderForEdit,
  editOrder,
  addOrder,
  orderApproval,
  orderExport
} from "../api/orderApi.js";

import {findCustomerAll} from "../api/customerApi.js";
import {findProductList} from "../api/productApi.js";

import {findByUserId} from "../api/addressApi.js";

import {ElMessage, ElLoading} from "element-plus"; // 引入 ElLoading
import dayjs from 'dayjs';

export default {
  name: "Order",
  data() {
    return {
      searchForm: {
        orderId: '',
        customerId: '',
        status: '',
        startTime: '',
        endTime: '',
      },
      customerOptions: [],
      statusOptions: [
        {value: -1, label: '审批失败'},
        {value: 0, label: '未审批'},
        {value: 1, label: '已审批，待付款'},
        {value: 2, label: '已付款，待发货'},
        {value: 3, label: '已到货，待收货'},
        {value: 4, label: '已收货'},
        // { value: 6, label: '已申请退货，待审核' },
        // { value: 7, label: '退货审核成功' },
      ],
      orderList: [],
      currentPage: 1,
      pageSize: 3, // 默认每页大小
      total: 0, // 总记录数
      orderDetail: [],
      detailDialogVisible: false,
      deleteOrderId: '',
      deleteCustomerName: '',
      deleteDialogVisible: false,
      editForm: {},
      editDialogVisible: false,
      addForm: {
        customerId: '',
        addressId: '', // 修改点3: 初始化 addressId
        items: [{
          productId: '',
          buyNum: 1,
          name: '',
          price: 0,
          sumPrice: 0
        }],
        totalPrice: 0
      },
      addDialogVisible: false,
      productOptions: [],
      productMap: {}, // 用于快速查找商品信息
      addressOptions: [], // 存储当前选中客户的地址列表
      addressMap: {}, // (可选) 地址ID到地址对象的映射
      addRules: {
        customerId: [{required: true, message: '请选择客户', trigger: 'change'}],
        addressId: [{required: true, message: '请选择地址', trigger: 'change'}],
      },
    };
  },
  // 添加 watch 监听 customerId 变化
  watch: {
    'addForm.customerId': {
      handler(newCustomerId) {
        this.fetchAddressesForCustomer(newCustomerId);
      },
      immediate: false // 组件创建时不立即执行，只有值变化时才执行
    }
  },
  created() {
    // 初始化时调用搜索，会带上默认的分页参数
    this.searchOrders();
    this.getCustomerOptions();
    this.getProductOptions();
  },
  methods: {
    // 导出数据
    async handleExport() {
      // 1. 收集当前搜索参数（与 searchOrders 一致）
      const exportParams = {
        ...this.searchForm,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      // 2. 将参数转为 URL 查询字符串
      const queryParams = new URLSearchParams();
      Object.keys(exportParams).forEach(key => {
        if (exportParams[key] !== '' && exportParams[key] != null) {
          queryParams.append(key, exportParams[key]);
        }
      });

      try {
        // 3. 调用导出接口（注意：必须使用 Blob 处理二进制文件流）
        const response = await orderExport(queryParams.toString());

        // 4. 检查响应类型是否为 blob 错误（即后端返回的是 JSON 错误）
        const contentType = response.headers['content-type'];
        if (contentType && contentType.includes('application/json')) {
          // 后端可能返回了错误信息（如权限不足、无数据等）
          const data = JSON.parse(await response.data.text());
          ElMessage.error(data.msg || '导出失败');
          return;
        }

        // 5. 创建 Blob 对象并触发下载
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;

        // 设置默认文件名（可由后端 Content-Disposition 决定）
        const contentDisposition = response.headers['content-disposition'];
        let fileName = '订单列表.xlsx';
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i);
          if (filenameMatch && filenameMatch[1]) {
            fileName = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
          }
        }
        link.setAttribute('download', fileName);

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        ElMessage.success('导出成功');
      } catch (err) {
        console.error('导出订单失败', err);
        ElMessage.error('导出失败，请检查网络或权限');
      }
    },
    // 支付
    async pay(orderId) {
      try {
        const res = await this.$store.dispatch('order/reqPay', {
          orderId
        });
        console.log(res); // "success"
        this.$message.success('支付已发起，请完成跳转');
      } catch (error) {
        console.error('支付失败:', error);
        this.$message.error('支付请求失败');
      }
    },
    // 审批
    async submitApproval(orderId) {
      const orderCode = orderId;
      const steps = [
        '库存检查中...',
        '一级审批中...',
        '财务审核中...',
        '订单审批提交中...'
      ];
      const successMessages = [
        '✅ 库存检查通过',
        '✅ 一级审批通过',
        '✅ 财务审核通过',
        `🎉 订单 ${orderCode} 审批通过！`
      ];

      // 创建全屏 loading
      const loading = ElLoading.service({
        lock: true,
        text: steps[0],
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
        customClass: 'approval-loading'
      });

      const updateLoadingText = (text) => {
        const el = document.querySelector('.el-loading-text');
        if (el) el.innerText = text;
      };

      try {
        // 模拟每一步
        for (let i = 0; i < steps.length; i++) {
          updateLoadingText(steps[i]);
          await new Promise(resolve => setTimeout(resolve, 800));
        }

        // 最后调用真实接口
        updateLoadingText('提交最终审批...');
        const {data} = await orderApproval({orderId});
        console.log(data);

        loading.close();

        if (data.code === 200) {
          this.$alert(
              successMessages.map(msg => `<p style="text-align: center; font-size: 16px; margin: 10px 0;">${msg}</p>`).join(''),
              '审批成功',
              {
                dangerouslyUseHTMLString: true,
                type: 'success',
                center: true,
                showClose: false,
                customClass: 'approval-success-dialog'
              }
          ).then(() => {
            this.searchOrders();
          });
        } else {
          ElMessage.error(data.data || '审批失败');
        }
      } catch (err) {
        loading.close();
        ElMessage.error('审批失败，请稍后重试');
      }
    },
    async getCustomerOptions() {
      try {
        let {data} = await findCustomerAll();
        // 确保 data.data 是数组，并过滤掉无效项
        const customers = Array.isArray(data.data) ? data.data : [];
        this.customerOptions = customers.filter(item => item && item.customerId != null);
      } catch (error) {
        console.error("获取客户列表失败:", error);
        this.customerOptions = [];
        ElMessage.error("获取客户列表失败");
      }
    },
    async getProductOptions() {
      try {
        let {data} = await findProductList();
        this.productOptions = data.data || [];
        // 构建 productId -> 商品对象的映射
        this.productMap = {};
        this.productOptions.forEach(prod => {
          this.productMap[prod.productId] = prod;
        });
      } catch (error) {
        console.error("获取商品列表失败:", error);
        this.productOptions = [];
        this.productMap = {};
        ElMessage.error("获取商品列表失败");
      }
    },
    // 获取地址的方法
    async fetchAddressesForCustomer(customerId) {
      // 清空之前的地址选项和选中项
      this.addressOptions = [];
      this.addForm.addressId = ''; // 清空地址选择

      if (!customerId) {
        // 如果没有选择客户，则不请求地址
        return;
      }

      try {
        // 假设 findByUserId 接收用户ID作为参数
        // 如果 customerId 实际上就是用户ID，则直接传入
        // 如果不是，需要根据 customerId 查询到对应的用户ID
        // 这里假设 customerId 就是用户ID
        const {data} = await findByUserId(customerId);
        if (data.code === 200) {
          this.addressOptions = data.data || []; // 假设返回的地址列表在 data.data 中

          // (可选) 构建地址ID到地址对象的映射
          this.addressMap = {};
          this.addressOptions.forEach(addr => {
            this.addressMap[addr.id] = addr;
          });

        } else {
          ElMessage.error(data.msg || '获取地址失败');
        }
      } catch (err) {
        console.error('获取地址失败', err);
        ElMessage.error('获取地址失败');
      }
    },
    // 修正：接收 productId 和 index
    handleProductChange(productId, index) {
      const item = this.addForm.items[index];
      const product = this.productMap[productId];
      if (product) {
        item.name = product.name;
        item.price = product.price;
        item.sumPrice = (item.buyNum * product.price).toFixed(2);
        this.calculateAddTotalPrice();
      }
    },
    async searchOrders() {
      // 1. 准备请求参数，包含分页信息
      const searchParams = {
        ...this.searchForm, // 包含现有的搜索条件
        pageNum: this.currentPage,  // 添加当前页码
        pageSize: this.pageSize    // 添加每页大小
      };

      try {
        // 2. 调用后端分页搜索接口
        const {data} = await findSearchOrders(searchParams);
        console.log(data);
        // 3. 处理后端返回结果
        if (data.code === 200) {
          // 4. 从 PageInfo 对象中提取数据
          const pageInfo = data.data; // 后端返回的 PageInfo 对象

          // 5. 更新订单列表
          this.orderList = pageInfo.list || [];

          // 6. 更新总记录数，这是 el-pagination 正常工作的关键
          this.total = pageInfo.total || 0;

          // 为每个订单项添加 statusName
          this.orderList.forEach(order => {
            const statusItem = this.statusOptions.find(item => item.value === order.status);
            order.statusName = statusItem ? statusItem.label : '';
          });
        } else {
          // 请求成功但业务失败
          ElMessage.error(data.msg || '获取订单列表失败');
          // 重置列表和总数
          this.orderList = [];
          this.total = 0;
        }
      } catch (err) {
        // 请求失败（网络错误等）
        console.error('搜索订单失败', err);
        ElMessage.error('搜索订单失败');
        // 重置列表和总数
        this.orderList = [];
        this.total = 0;
      }
    },
    resetSearch() {
      // 重置搜索表单
      this.searchForm = {
        orderId: '', customerId: '', status: '', startTime: '', endTime: ''
      };
      // 重置分页参数到第一页
      this.currentPage = 1;
      // 触发搜索
      this.searchOrders();
    },
    // 处理每页显示条数改变
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      // 通常切换每页大小时，会回到第一页
      this.currentPage = 1;
      // 重新搜索
      this.searchOrders();
    },
    // 处理当前页改变
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      // 重新搜索
      this.searchOrders();
    },
    async handleDetail(orderId) {
      try {
        const {data} = await findOrderDetail(orderId);
        if (data.code === 200) {
          this.orderDetail = data.data;
          this.detailDialogVisible = true;
        } else {
          ElMessage.error(data.msg || '获取订单详情失败');
        }
      } catch (err) {
        console.error('获取订单详情失败', err);
        ElMessage.error('获取订单详情失败');
      }
    },
    handleDelete(orderId, customerName) {
      this.deleteOrderId = orderId;
      this.deleteCustomerName = customerName;
      this.deleteDialogVisible = true;
    },
    async confirmDelete() {
      try {
        const {data} = await deleteOrder(this.deleteOrderId);
        if (data.code === 200) {
          ElMessage.success('删除成功');
          this.deleteDialogVisible = false;
          // 删除后刷新当前页
          this.searchOrders();
        } else {
          ElMessage.error(data.msg || '删除失败');
        }
      } catch (err) {
        console.error('删除订单失败', err);
        ElMessage.error('删除失败');
      }
    },
    async handleEdit(orderId) {
      try {
        const {data} = await getOrderForEdit(orderId);
        if (data.code === 200) {
          const orderData = data.data.order;
          this.editForm = {
            orderId: orderData.orderId,
            customerId: orderData.customerId,
            customerName: orderData.name,
            address: orderData.address,
            totalPrice: orderData.totalPrice,
            status: orderData.status,
            createTime: orderData.createTime,
            items: data.data.orderItems.map(item => ({
              ...item,
              buyNum: parseFloat(item.buyNum),
              sumPrice: parseFloat(item.sumPrice)
            }))
          };
          this.editDialogVisible = true;
        } else {
          ElMessage.error(data.msg || "获取订单信息失败");
        }
      } catch (err) {
        console.error("获取订单信息失败", err);
        ElMessage.error("获取订单信息失败");
      }
    },
    async saveEdit() {
      try {
        const dataToSendToBackend = {
          orderId: this.editForm.orderId,
          customerId: this.editForm.customerId,
          totalPrice: this.editForm.totalPrice,
          orderItems: this.editForm.items.map(item => ({
            itemId: item.itemId || null,
            orderId: this.editForm.orderId,
            productId: item.productId,
            buyNum: item.buyNum,
            price: item.price,
            sumPrice: item.sumPrice,
            name: item.name,
            createTime: item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                : dayjs().format('YYYY-MM-DD HH:mm:ss')
          }))
        };
        const {data} = await editOrder(dataToSendToBackend);
        console.log(data);
        if (data.code === 200) {
          ElMessage.success(data.data);
          this.editDialogVisible = false;
          this.searchOrders(); // 修改后刷新列表
        } else {
          ElMessage.error(data.data || '修改失败');
        }
      } catch (err) {
        console.error('修改订单失败', err);
        ElMessage.error('修改失败');
      }
    },
    calculateItemSum(item) {
      const price = parseFloat(item.price) || 0;
      const buyNum = parseFloat(item.buyNum) || 0;
      item.sumPrice = Number((buyNum * price).toFixed(2));
      this.calculateTotalPrice();
    },
    calculateTotalPrice() {
      let total = 0;
      this.editForm.items.forEach(item => {
        total += parseFloat(item.sumPrice) || 0;
      });
      this.editForm.totalPrice = Number(total.toFixed(2));
    },
    calculateAddItemSum(index) {
      const item = this.addForm.items[index];
      const product = this.productMap[item.productId];
      if (product) {
        item.sumPrice = Number((item.buyNum * product.price).toFixed(2));
        this.calculateAddTotalPrice();
      }
    },
    calculateAddTotalPrice() {
      let total = 0;
      this.addForm.items.forEach(item => {
        total += parseFloat(item.sumPrice) || 0;
      });
      this.addForm.totalPrice = Number(total.toFixed(2)); // Number 类型
    },
    removeAddItem(index) {
      this.addForm.items.splice(index, 1);
      if (this.addForm.items.length === 0) {
        this.addNewItem();
      } else {
        this.calculateAddTotalPrice();
      }
    },
    addNewItem() {
      this.addForm.items.push({
        productId: '',
        buyNum: 1,
        name: '',
        price: 0,
        sumPrice: 0
      });
    },

    async submitAdd() {
      // 1. 表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;

        const validItems = this.addForm.items.filter(item => item.productId && item.buyNum > 0);
        if (validItems.length === 0) {
          ElMessage.error('请至少添加一个有效的商品');
          return;
        }

        // 2. 准备数据
        const orderDataToSend = {
          customerId: this.addForm.customerId,
          addressId: this.addForm.addressId,
          orderItems: validItems.map(item => ({
            productId: item.productId,
            buyNum: item.buyNum
          }))
        };

        // --- 加载动画逻辑 ---
        const loadingInstance = ElLoading.service({
          lock: true,
          text: '订单提交中，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        const minLoadingTime = 500; // 最短显示 500ms
        const startTime = Date.now();

        let addSuccess = false;
        let addErrorMessage = '添加订单失败';
        let shouldRefresh = false; // 标志位：是否需要刷新

        try {
          const {data} = await addOrder(orderDataToSend);
          console.log(data);
          if (data.code === 200) {
            addSuccess = true;
            shouldRefresh = true; // 标记需要刷新
            // --- 关键修改：添加延迟 ---
            // 假设后端处理需要 3 秒，这里等待 3.5 秒确保完成
            // 可以根据实际情况调整这个时间
            const PROCESSING_DELAY = 2500; // 2.5 秒
            await new Promise(resolve => setTimeout(resolve, PROCESSING_DELAY));
            // --- 关键修改结束 ---
          } else {
            addErrorMessage = data.data || '添加订单失败';
          }
        } catch (err) {
          console.error('添加订单失败', err);
          addErrorMessage = '网络错误，添加订单失败';
        } finally {
          const elapsedTime = Date.now() - startTime;
          const remainingTime = Math.max(0, minLoadingTime - elapsedTime);

          await new Promise(resolve => setTimeout(resolve, remainingTime));
          loadingInstance.close();

          if (addSuccess) {
            ElMessage.success('添加订单成功');
            this.addDialogVisible = false;
            this.resetAddForm();

            // --- 关键修改：仅在成功且标记需要刷新时才刷新 ---
            if (shouldRefresh) {
              this.currentPage = 1; // 跳转到第一页查看新订单
              await this.searchOrders(); // 等待列表刷新完成
            }
            // --- 关键修改结束 ---
          } else {
            ElMessage.error(addErrorMessage);
          }
        }
      });
    },
    resetAddForm() {
      this.addForm = {
        customerId: '',
        addressId: '', // 修改点9: 重置时也清空 addressId
        items: [{
          productId: '',
          buyNum: 1,
          name: '',
          price: 0,
          sumPrice: 0
        }],
        totalPrice: 0
      };
      // 清空地址选项
      this.addressOptions = [];
      if (this.$refs.addFormRef) {
        this.$refs.addFormRef.resetFields();
      }
    }
  }
};
</script>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 使用 :deep() 代替 /deep/ */
:deep(.el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}
</style>



